const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config({ path: path.join(__dirname, '..', '.env') });

// 数据库连接配置
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'password',
  multipleStatements: true // 允许执行多条SQL语句
};

async function initDatabase() {
  let connection;

  try {
    // 读取SQL脚本
    const sqlPath = path.join(__dirname, '..', 'sql', 'schema.sql');
    const sqlScript = fs.readFileSync(sqlPath, 'utf8');

    console.log('正在连接到MySQL服务器...');
    connection = await mysql.createConnection(dbConfig);
    
    console.log('正在执行SQL脚本...');
    await connection.query(sqlScript);
    
    console.log('数据库初始化成功！');
  } catch (error) {
    console.error('数据库初始化失败:', error.message);
    process.exit(1);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

// 执行初始化
initDatabase(); 